﻿using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using System;
using UnityEngine.UI;

public class ReadWriteTxt : MonoBehaviour
{
    private static ReadWriteTxt _instance;
    public static ReadWriteTxt Instance
    {
        get
        {
            return _instance;
        }
    }

    private void Awake()
    {
        _instance = this;
    }


    /// <summary>
    /// 创建txt文件
    /// </summary>
    /// <param name="path">路径</param>
    /// <param name="name">文件名</param>
    /// <param name="info">内容</param>
    public void CreateFile(string path, string name, string info)
    {
        StreamWriter sw;
        FileInfo t = new FileInfo(path + "//" + name);
        if (!t.Exists)
        {
            sw = t.CreateText();
        }
        else
        {
            sw = t.AppendText();
        }
        sw.WriteLine(info);
        sw.Close();
        sw.Dispose();

        Debug.Log("[创建或者增加文件] --> " + name);
    }

    /// <summary>
    /// 读取txt文件
    /// </summary>
    /// <param name="path">路径</param>
    /// <param name="name">文件名</param>
    /// <returns>txt内容列表</returns>
    public List<string> LoadFile(string path, string name)
    {
        StreamReader sr = null;
        try
        {
            sr = File.OpenText(path + "//" + name);
        }
        catch (Exception e)
        {
            //路径与名称未找到文件则直接返回空
            return null;
        }
        string line;
        List<string> arrlist = new List<string>();
        while ((line = sr.ReadLine()) != null)
        {
            arrlist.Add(line);
        }
        sr.Close();
        sr.Dispose();
        Debug.Log("[读取文件] --> " + name);
        return arrlist;
    }

    /// <summary>
    /// 删除txt文件
    /// </summary>
    /// <param name="path">路径</param>
    /// <param name="name">文件名</param>
    public void DeleteFile(string path, string name)
    {
        File.Delete(path + "//" + name);
        Debug.Log("[删除文件] --> " + name);
    }
}